<script setup lang="ts">
// import type { Action } from 'element-plus';

import type { Ref } from 'vue';

import type { Scene } from '../index';

import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import {mapApi} from '#/api';
import {
  BiGlobe,
  ElFullScreen,
  ElHomeFilled,
  PixelarticonsGrid,
  SimpleLineIconsQuestion,
  SvgMapIcon,
  SystemUiconsWrapBack,
} from '@vben/icons';

import { StorageManager } from '@vben-core/shared/cache';

// @ts-ignore
import {
  ElButton,
  ElCol,
  ElDialog,
  ElDivider,
  ElIcon,
  ElInput,
  ElLoading,
  ElMessage,
  ElPopover,
  ElRow,
  ElSpace,
  ElTag,
  ElTooltip,
} from 'element-plus';
import mapboxGl from 'mapbox-gl';

import { useMapStore, useSceneStore } from '#/store';
import { layerRenderUtil } from '#/utils';

import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css';
import { useRoute } from 'vue-router'
import { panelYearRangeEmits } from 'element-plus/es/components/date-picker/src/props/panel-year-range.mjs';

const route = useRoute()
const mapId = route.params.id 
const { initRender } = layerRenderUtil();
const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});
const mapStore = useMapStore();

mapboxGl.accessToken =
  'pk.eyJ1IjoibmluamFhIiwiYSI6ImNsYXYzd3JwaDAyMGwzdm44ZmI3M212eHQifQ.h_dGMMOvQXNfmheNd0_j8A';
const sceneStore = useSceneStore();
const mapbox = reactive({
  map: null as any,
});
const router = useRouter();
const mapContainer: Ref<HTMLElement | undefined> = ref();
const loadingText = ref('地图加载中...');
const zoomText = ref();
const showCenter = ref('');
const saveSceneDialog = ref(false);
const isReadonly = ref(true);
const mapMode = ref('mercator');
const mapModeList = ref([
  {
    id: 1,
    name: '平面',
    value: 'mercator',
  },
  {
    id: 2,
    name: '3D',
    value: 'globe',
  },
]);

let mapUrl = mapStore.publishMap.mapUrl;

// 初始化空地图
const initMap = () => {
  return new Promise((resolve) => {
    mapbox.map = new mapboxGl.Map({
      container: 'map-container',
      // style:'http://172.21.252.218:8080/map-style/5a564b34-a88c-424e-a81e-aa0605b30942/4b59b841-1e28-4ddb-92ae-7329c78138af.json',
      style: mapUrl,
      center: [118.9, 32.08],
      zoom: 6,
      // projection: "globe",
      preserveDrawingBuffer: true,
      attributionControl: false,
    });

    mapbox.map.on('load', () => {
      resolve('地图初始化成功！正在加载场景配置项...');
    });

    const scale = new mapboxGl.ScaleControl({
      maxWidth: 120,
    });
    mapbox.map.addControl(scale);
    scale.setUnit('metric');

    mapbox.map.on('zoom', () => {
      zoomText.value = mapbox.map.getZoom().toFixed(2);
    });
    mapbox.map.on('mousemove', (e: any) => {
      showCenter.value = `(${String(e.lngLat.lng.toFixed(5))}，${String(
        e.lngLat.lat.toFixed(5),
      )})`;
    });
  });
};

const toggleMapMode = (mode: any, init: boolean = false) => {
  const { value, name } = mode;
  if (value === mapMode.value) return;
  mapMode.value = value;
  mapbox.map.setProjection(value);
  if (value === 'globe') {
    mapbox.map.setFog({});
  } else {
    mapbox.map.setFog(null);
  }
  if (!init) {
    // update store
    sceneStore.currentSceneConfig.mapParams.mapMode =
      value === 'mercator' ? 0 : 1;
    ElMessage.success(`已切换至${name}模式`);
  }
};

const initMapMode = () => {
  const mode = sceneStore.currentSceneConfig.mapParams.mapMode
    ? {
        id: 2,
        name: '3D',
        value: 'globe',
      }
    : {
        id: 1,
        name: '平面',
        value: 'mercator',
      };
  toggleMapMode(mode, true);
};

const initMapState = (duration = 1500) => {
  mapbox.map.easeTo({
    center: sceneStore.currentSceneConfig.mapParams.center, // 目标中心点坐标
    zoom: sceneStore.currentSceneConfig.mapParams.zoom, // 目标缩放级别
    bearing: sceneStore.currentSceneConfig.pos.bearing, // 目标旋转角度（以度为单位，可选）
    pitch: sceneStore.currentSceneConfig.pos.pitch, // 目标俯仰角（以度为单位，可选）
    duration, // 动画持续时间（以毫秒为单位，可选）
  });
};

const handletoggleFullScreen = () => {
  const mapContainer = mapbox.map.getContainer();
  //  兼容不同浏览器
  const rfs =
    mapContainer.requestFullscreen ||
    mapContainer.webkitRequestFullScreen ||
    mapContainer.mozRequestFullScreen ||
    mapContainer.msRequestFullscreen;

  if (rfs) {
    rfs.call(mapContainer);
  }
};

const backScene = () => {
  router.back();
};

onMounted(async () => {
  // 1. 从存储中获取场景数据并设置到store
  const editingScene = storageManager.getItem('editingScene') as Scene;
  sceneStore.setEditingScene(editingScene);

  // 2. 初始化加载动画
  const sceneLoading = ElLoading.service({
    lock: true,
    text: loadingText.value, // 初始文本："场景加载中..."
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    if(!mapUrl && mapId){
      mapUrl = await mapApi.getMapUrl(mapId as string);
    }
    loadingText.value = '初始化地图中...';
    sceneLoading.setText(loadingText.value);
    await initMap(); // 等待地图完全加载

    // 初始化渲染和地图模式
    loadingText.value = '初始化渲染...';
    sceneLoading.setText(loadingText.value);
    initRender(mapbox.map);
    initMapMode();

    loadingText.value = '加载完成';
    sceneLoading.close();
  } catch (error) {
    loadingText.value = '加载失败，请重试';
    sceneLoading.setText(loadingText.value);
    console.error('初始化失败：', error);
    // 3秒后自动关闭错误提示
    setTimeout(() => sceneLoading.close(), 3000);
  }
});
</script>

<template>
  <div class="allcontainer">
    <div class="header">
      <div class="left-btn">
        <ElIcon size="22" color="#ccc" @click="backScene">
          <SystemUiconsWrapBack />
        </ElIcon>
      </div>
      <div class="title">
        <ElIcon size="22">
          <SvgMapIcon />
        </ElIcon>
        <span>{{ sceneStore.editingScene.sceneName }}</span>
      </div>
      <div class="right-btn">
        <ElSpace :size="22">
          <ElTooltip placement="bottom" content="全屏">
            <ElIcon size="21" color="#ccc" @click="handletoggleFullScreen">
              <ElFullScreen />
            </ElIcon>
          </ElTooltip>
          <ElTooltip placement="bottom" content="帮助">
            <ElIcon size="21" color="#ccc">
              <SimpleLineIconsQuestion />
            </ElIcon>
          </ElTooltip>
        </ElSpace>
      </div>
    </div>
    <div class="body">
      <div class="map-box">
        <div id="map-container" ref="mapContainer">
          <ElTag class="mapZoomLngLat" type="info">
            Zoom:{{ zoomText }} &nbsp; LngLat:{{ showCenter }}
          </ElTag>

          <div class="homemap-control">
            <ElIcon
              class="control-btn"
              size="27"
              title="回到初始状态"
              @click="initMapState(0)"
            >
              <ElHomeFilled />
            </ElIcon>
          </div>
          <div class="mapmode-control">
            <ElPopover
              placement="left-end"
              :width="80"
              trigger="click"
              :teleported="false"
              transition="none"
              :hide-after="0"
              :popper-style="{ minWidth: '80px', padding: '5px' }"
            >
              <template #default>
                <div class="mapmode-sub-control">
                  <ElIcon
                    size="27"
                    class="sub-control-btn"
                    title="平面"
                    :class="{
                      'mode-active': mapMode === mapModeList[0]?.value,
                    }"
                    @click="toggleMapMode(mapModeList[0])"
                  >
                    <PixelarticonsGrid />
                  </ElIcon>
                  <ElDivider
                    direction="vertical"
                    border-style="hidden"
                    style="margin-right: 3px; margin-left: 3px"
                  />
                  <ElIcon
                    size="24"
                    class="sub-control-btn"
                    title="3D"
                    :class="{
                      'mode-active': mapMode === mapModeList[1]?.value,
                    }"
                    @click="toggleMapMode(mapModeList[1])"
                  >
                    <BiGlobe />
                  </ElIcon>
                </div>
              </template>
              <template #reference>
                <ElIcon
                  v-if="mapMode === 'mercator'"
                  size="27"
                  class="control-btn"
                  title="平面"
                >
                  <PixelarticonsGrid />
                </ElIcon>
                <ElIcon v-else size="25" class="control-btn" title="3D">
                  <BiGlobe />
                </ElIcon>
              </template>
            </ElPopover>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="save-scene-dialog">
    <ElDialog
      draggable
      class="dialog-title"
      v-model="saveSceneDialog"
      width="20%"
      align-center
      destroy-on-close
    >
      <template #header>
        <div class="my-header">
          <h4 style="color: rgb(48 45 45)">保存场景</h4>
        </div>
        <ElDivider style="padding: 0; margin: 0" />
      </template>
      <ElDivider
        border-style="hidden"
        style="margin-top: 20px; margin-bottom: 0"
      />
      <ElRow type="flex" align="middle">
        <div class="row-style">
          <ElCol :span="5">
            <span>场景类型：</span>
          </ElCol>
          <ElCol :span="19">
            <ElInput
              :disabled="true"
              size="default"
              placeholder="地理数据可视化场景"
            />
          </ElCol>
        </div>
      </ElRow>
      <ElRow type="flex" align="middle">
        <div class="row-style">
          <ElCol :span="5">
            <span>场景名称：</span>
          </ElCol>
          <ElCol :span="19">
            <ElInput
              v-model.trim="sceneStore.editingScene.sceneName"
              :readonly="isReadonly"
              size="default"
              @blur="isReadonly = true"
            >
              <template #append>
                <ElButton
                  type="primary"
                  size="default"
                  text
                  @click="isReadonly = false"
                  title="单击以更改"
                >
                  更改
                </ElButton>
              </template>
            </ElInput>
          </ElCol>
        </div>
      </ElRow>
      <ElDivider
        border-style="hidden"
        style="margin-top: 0; margin-bottom: 20px"
      />
    </ElDialog>
  </div>
</template>

<style scoped lang="scss">
@keyframes fade-in-right {
  from {
    right: 8vw;
    opacity: 0;
  }

  to {
    right: 9vw;
    opacity: 1;
  }
}

.menuCon {
  display: flex;
  flex-direction: column;
  height: 100%;
  border-right: 1px solid rgb(168 166 166);
}

.editContainer,
.settingPannel {
  box-sizing: border-box;
  flex-shrink: 0;
  width: 100%;
  width: 340px;
  height: 100%;
  // overflow: hidden;
  border-right: 1px solid rgb(202 202 202);
}

/* .resourceManagement {
  width: 100%;
  height: 100%;
} */

/* .dataSourcePannel {
  width: 100%;
  height: 0%;
} */

.dataSourcePannel2 {
  width: 100%;
  height: 100%;

  /* flex: 1; */
}

.layerPannel {
  width: 100%;
  height: 100%;

  /* flex: 1; */
}

.map-box {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  // padding: 5px 0 0 0;
  // background-color: #e4e4e4;
  background-color: #f2f3f7;
  border-top: 1px solid #fff;
}

#map-container {
  position: relative;
  z-index: 10;
  flex: 1;
  width: 100%;
  // height: 100%;
}

.allcontainer {
  display: flex;
  flex-direction: column;
  width: 100vw;
  height: 100vh;
  overflow: hidden;

  /* 禁用滚动 */
}

.header {
  z-index: 11;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 50px;
  // background-color: #fff;
  background-color: #2e3138;
  border-bottom: rgb(175 175 175 / 50%) 1px solid;
  box-shadow: -10px 10px 4px -12px rgb(0 0 0 / 50%);

  /* inset 表示内阴影 */

  .common-btn {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 80%;
  }

  .left-btn {
    /* stylelint-disable-next-line at-rule-no-unknown */
    @extend .common-btn;

    width: 56px;
    border-right: #ccc 1px solid;
  }

  .right-btn {
    /* stylelint-disable-next-line at-rule-no-unknown */
    @extend .common-btn;

    padding-right: 22px;
    // width: 120px;
  }

  .common-btn .el-icon:hover {
    color: #fff;
    cursor: pointer;
  }

  .title {
    display: flex;
    align-items: center;
    font-size: 1.2rem;
    font-weight: 600;
    // color: #333;
    color: #ccc;
    letter-spacing: 1px;

    span {
      // width: 100px;
      height: 30px;
      margin-left: 5px;
      line-height: 30px;
    }
  }
}

.body {
  display: flex;
  flex: 1;
  width: 100%;
}

.menuItemsCon {
  height: 100%;
}

.menu-btn {
  /* 导航栏实际高度比header高，遮住了 */
  z-index: 10;
  display: flex;

  /* text-align: center; */
  align-items: center;
  justify-content: center;
  height: 57px;
  color: #bababa;
  cursor: pointer;
  user-select: none;
  background-color: #2b2b2b;

  &:hover {
    color: #fff;
    background-color: #151515;
  }
}

.icon {
  width: 1em;
  height: 1em;
  overflow: hidden;
  vertical-align: -0.15em;
  fill: currentcolor;
}

.el-menu {
  --el-menu-base-level-padding: 16px;

  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  user-select: none;
  border: none;

  // .el-menu-item {
  //   padding: 0 calc(var(--el-menu-base-level-padding) + 8px) 0
  //     var(--el-menu-base-level-padding);
  // }
}

.el-menu-item.is-active {
  width: 100%;
  font-weight: bold;
  background-color: #151515 !important;
}

.el-menu-item:hover {
  /* width: 100%; */
  color: #fff;
  background-color: #151515;
}

.el-menu-item.is-active::before {
  position: absolute;
  top: 0;
  left: 0;
  display: inline-block;
  width: 3px;
  height: 100%;
  content: '';
  background-color: #2f89fc;
}

/* 隐藏logo */
:deep(.mapboxgl-ctrl-logo) {
  display: none !important;
}

:deep(.mapboxgl-ctrl-bottom-right) {
  display: none !important;
}

.mapZoomLngLat {
  position: absolute;
  right: 60px;
  bottom: 10px;
  z-index: 10;
  font-size: 13px;
  background-color: #fff !important;
}

.mapStyleBtn {
  position: absolute;
  top: 40px;
  right: 60px;
  z-index: 10;
  font-size: 13px;
  background-color: #fff !important;
}

.mapmode-control {
  position: absolute;
  right: 20px;
  bottom: 70px;
  z-index: 10;

  .mapmode-sub-control {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 70px;
    height: 30px;

    .sub-control-btn {
      width: 30px;
      height: 100%;
      padding: 2px;
      border: #e7e7e7 solid 2px;
      border-radius: 5px;

      &:not(.mode-active):hover {
        color: #2f89fc;
        cursor: pointer;
        border: #2f89fc solid 2px;
      }
    }

    .mode-active {
      color: #2f89fc;
      border: #2f89fc solid 2px;
    }
  }
}

.basemap-control {
  position: absolute;
  right: 20px;
  bottom: 20px;
  z-index: 10;
}

.homemap-control {
  position: absolute;
  right: 20px;
  bottom: 120px;
  z-index: 10;
}

.export-control {
  position: absolute;
  right: 20px;
  bottom: 170px;
  z-index: 10;
}

.export-control,
.mapmode-control,
.basemap-control,
.homemap-control {
  .control-btn {
    width: 40px;
    height: 40px;
    color: #4d4d4d;
    background-color: rgb(255 255 255 / 50%);
    border: 1px solid rgb(175 175 175 / 50%);
    border-radius: 50%;
    box-shadow:
      0 4px 6px rgb(0 0 0 / 10%),
      0 1px 3px rgb(0 0 0 / 8%);

    /* 初始阴影效果 */
    transition: all 0.3s ease;

    &:hover {
      color: #2f89fc;
      cursor: pointer;
      background-color: rgb(255 255 255 / 80%);
      box-shadow:
        0 15px 30px rgb(0 0 0 / 20%),
        0 10px 15px rgb(0 0 0 / 10%);

      /* 悬浮时的更大阴影 */
      transform: translateY(-6px);

      /* 上浮效果 */
    }
  }
}

.animation-control {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
}

/* 保存对话框 */
.my-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 40px;
  padding-top: 10px;
  padding-bottom: 5px;
  padding-left: 20px;
  font-size: 18px;
}

:deep(.save-scene-dialog .el-dialog) {
  height: auto;
  border-radius: 20px;
  box-shadow: 0 0 50px rgb(0 0 0 / 50%);
}

.row-style {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 10px 20px;
}

.mybtn {
  width: 80px;
  height: 30px;
  font-weight: bolder;
  letter-spacing: 1px;
  border-radius: 3px;
}

/* 大模型css */
.btn {
  position: absolute;
  right: 2vw;
  bottom: 4vh;
  z-index: 999;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 45px;
  font-family: Dosis, sans-serif;
  font-size: 24px;
  color: white;
  cursor: pointer;
  background-image: linear-gradient(135deg, #fff 0%, #fff 100%);
  border: none;
  border-radius: 30px;
  outline: none;
  box-shadow: 0 20px 30px -6px rgb(255 255 255 / 50%);
  transition: all 0.3s ease-in-out;
}

.btn:active {
  opacity: 0.5;
}

/* robot */
.aiAssitant {
  bottom: 2vh;
  z-index: 999;
  display: flex;
  justify-content: center;
}

.aiImage {
  display: flex;
  align-items: center;
  justify-content: center;
}

.aiImage:hover {
  scale: 1.1;
}

.dianwo {
  font-size: small;
  color: #000;
}

.dianwo:hover {
  color: #5ca7f3;
  cursor: pointer;
}

.aiChatPannel {
  position: absolute;
  right: 9vw;
  bottom: 4vh;
  z-index: 1999;
  width: 25vw;
  height: 66vh;
  padding: 5px;
  background-color: rgb(226 232 240);
  border-radius: 15px;
  box-shadow: -10px 12px 8px -12px #000;
  animation: fade-in-right 0.5s forwards;
}

.draw-result-marker {
  padding: 4px 8px;
  font-size: 12px;
  white-space: nowrap;
  background: white;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgb(0 0 0 / 30%);
}
</style>
